<?php

class AuctionController extends Client_Controller {

    public function init() {
        parent::init();
        $this->setActiveCat(985);
        $this->_table = new Client_Table_Auction_Auction();
    }

    //public function indexAction() {
    //    $this->_redirect("/" . $this->controller."/auction/");
    //}
    
    //-------------------------FORNT----------------------
    public function lotsAction() {
        $id = $this->_request->getParam('id',0);
        $filters = array();
        $table_lots = new Client_Table_Auction_Lots();

        $form = new Llib_Form($this->_request);

        if ($this->_request->isPost()) {
            $filters['by_id'] = $this->_request->getParam('by_id', '');
            $filters['by_region'] = $this->_getParam('by_region', 0);
            $filters['by_district'] = $this->_getParam('by_district', 0);
            $filters['by_town'] = $this->_getParam('by_town', 0);
        }

        $filters = $this->SessionVarsEx($filters, array('by_id', 'by_region', 'by_district', 'by_town'), $this->_request->getParam('reset', false));
        
        if (!($id > 0)) $filters['showAll'] = true;
        else $filters['id_auction'] = $id;
        
        $id_region = $filters['by_region'];
        $id_district = $filters['by_district'];
        $id_town = $filters['by_town'];

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array('link' => "/" . $this->controller . "/lot-card/"));//, 'link_fields'=>array('cad_num')"/view-lot-front/" . $id . "/id-lot/"
        $lclm->AddColumn('Номер лота', 'id', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Кадастровий номер', 'cad_num', array('width' => '10%', 'sort' => 1));
        $lclm->AddColumn('Площа (га)', 'area', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Адреса', 'parcel_address', array('width' => '30%', 'sort' => 1));
        $lclm->AddColumn('Цільове призначення', 'purpose', array('width' => '40%', 'sort' => 1));
        $lclm->AddColumn('Дата аукціона', 'start_date', array('width' => '10%', 'sort' => 1));

        $lclm->AddData($table_lots->getDataList($lclm->page, $lclm->s, $lclm->pager_count, $filters));
        
        $filters['id_region'] = $this->_table->addressGetRegions($id_region);
        $filters['id_district'] = $this->_table->addressGetDistricts($id_region, $id_district);
        $filters['id_town'] = $this->_table->addressGetTowns($id_region, $id_district, $id_town);
        if ($id > 0)
            $filters['executor'] = $this->_table->getAuctionExecutor($id);
        $form->AddData($filters);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }
    
    public function indexAction() {
    //public function auctionAction() {

        $form = new Llib_Form($this->_request);
        $filters = array();

        if ($this->_request->isPost()) {
            $filters['by_id'] = $this->_request->getParam('by_id', '');
            $filters['by_date'] = $this->_request->getParam('by_date', '');
            $filters['from_date'] = $this->_request->getParam('from_date', '');
            $filters['to_date'] = $this->_request->getParam('to_date', '');
            $filters['by_region'] = $this->_getParam('by_region', 0);
            $filters['by_district'] = $this->_getParam('by_district', 0);
            $filters['by_town'] = $this->_getParam('by_town', 0);
        }

        $filters = $this->SessionVarsEx($filters, array('by_id', 'by_date', 'from_date', 'to_date', 'by_region', 'by_district', 'by_town'), $this->_request->getParam('reset', false));

        $id_region = $filters['by_region'];
        $id_district = $filters['by_district'];
        $id_town = $filters['by_town'];

        $filters['id_region'] = $this->_table->addressGetRegions($id_region);
        $filters['id_district'] = $this->_table->addressGetDistricts($id_region, $id_district);
        $filters['id_town'] = $this->_table->addressGetTowns($id_region, $id_district, $id_town);

        $form->AddData($filters);

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array('link' => "/" . $this->controller . "/lots/"));
        $lclm->AddColumn('Номер аукціона', 'id', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Дата проведення', 'start_date', array('width' => '15%', 'sort' => 1));
        $lclm->AddColumn('Область', 'region', array('width' => '15%', 'sort' => 1));
        $lclm->AddColumn('Район', 'district', array('width' => '15%', 'sort' => 1));
        $lclm->AddColumn('Населений пункт', 'town', array('width' => '15%', 'sort' => 1));
        $lclm->AddColumn('Місце проведення', 'place', array('width' => '35%', 'sort' => 1));

        $lclm->AddData($this->_table->getDataList($lclm->page, $lclm->s, $lclm->pager_count, $filters));

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }
    
    
    
    public function lotCardAction() {
        $id = intval($this->_request->getParam('id'));

        if (empty($id)) $this->_redirect('/error/e404');

        $form = new Llib_Form($this->_request);
        $table_lots = new Client_Table_Auction_Lots();
        $data = $table_lots->getDataRow($id);
        if(isset($data['id_status']) && $data['id_status'] == 11){
            $table_attaches = new Client_Table_Auction_Attaches();
            $add_data = $table_attaches->getVideoFile($id);
            $add_data['video_path'] = $this->_http_files . $add_data['video_path'];
            $data = array_merge($data, $add_data);
        }
        
        $data = array_merge($data, $table_lots->getLotFilesCount($id));
        $form->AddData($data);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    
    public function ajaxDistrictsReloadAction() {
        $id_region = intval(@$_REQUEST['id_region']);

        echo "<option value='0'>-- Не вказано --</option>";

        if (is_numeric($id_region) && !empty($id_region)) {
            $items = $this->_table->addressGetDistricts($id_region);

            if (!empty($items) && is_array($items)) {
                foreach ($items as $value)
                    echo sprintf("<option value='%d'>%s</option>", $value['id'], $value['name']);
            }
        }

        die();
    }

    public function ajaxTownReloadAction() {
        $id_region = intval(@$_REQUEST['id_region']);
        $id_district = intval(@$_REQUEST['id_district']);

        echo "<option value='0'>-- Не вказано --</option>";

        if (is_numeric($id_region) && !empty($id_region) && is_numeric($id_district) && !empty($id_district)) {
            $items = $this->_table->addressGetTowns($id_region, $id_district);

            if (!empty($items) && is_array($items)) {
                foreach ($items as $value)
                    echo sprintf("<option value='%d'>%s</option>", $value['id'], $value['name']);
            }
        }

        die();
    }    

    public function downloadAttachesAction(){
      $form = new Llib_Form($this->_request);
      $d = $form->GetPostedData();
      $res = array();

      if(!($d['id'] > 0)) $this->_redirect('/error/e404');
      else{
          $table_attaches = new Client_Table_Auction_Attaches();
          $selectedAttacheList = $table_attaches->GetDataList(0, '', 0, $d);

          if(!empty($selectedAttacheList)) $res = $this->generateZipFile($selectedAttacheList,$d['id']);
          if(!empty($res) && @$res['full_path']!='' && @$res['file']!='')
              $res = $this->downloadAttachment($res['full_path'],$res['file']);
      }

      if(!empty($res) && ($res['err_code']>0 || ($res['error']!='' && $res['error']!='null'))){
          $this->startContent();
            $this->view->xmlWriter->startElement("Main");
                    $this->view->xmlWriter->writeAttribute('id', $d['id']);
                    $this->view->assign('error', $res);
            $this->view->xmlWriter->endElement();
          $this->view->xmlWriter->endElement();
      }else {
      	$table_attaches->recordDwnldRequest(array('id_lot'=>$d['id'], 'ip_recipient'=>$this->get_ip_address()));
      }
  	}
  
	private function get_ip_address() {
		$server_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
	    foreach ($server_keys as $key) {
	        if (array_key_exists($key, $_SERVER) === true) {
	            foreach (explode(',', $_SERVER[$key]) as $ip) {
	                if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
	                    return $ip;
	                }
	            }
	        }
	    }
	}
    
  	private function generateZipFile($data,$id){
      //ignore_user_abort(true);
      //set_time_limit(0);

        $zipPath = '/zip/'/*.$this->_user->id.'/'*/.date('Y_m_d',time());
        if(!$this->_files->CreateFolderRecursive('tmp'.$zipPath)) return array('error'=>$this->_files->GetError());
        $zipfile = 'lot_'.$id.".zip";

        $ZipArj = new ZipArchive();
        foreach ($data as $rows) {

            $rows['file_path'] = $this->_path_files.$rows['file_path'].'/'.$rows['file_name'];

            if (file_exists($rows['file_path']) && is_file($rows['file_path'])){
                $err_code = $ZipArj->open($this->_path_tmp.$zipPath.'/'.$zipfile,ZIPARCHIVE::CREATE);
                if ($err_code !== TRUE) {
                    $res['error']="Error opening Zip File: <".$zipPath.'/'.$zipfile.">\n";//, ZIPARCHIVE::CREATE
                    $res['err_code']=$err_code;

                    $ZipArj->close();

                    unset($data);
                    clearstatcache();

                    return $res;
                }
                $ZipArj->addFile($rows['file_path'],$this->tstring_filename($rows['name']));//
            }
        }
        $ZipArj->close();

        clearstatcache();
        unset($data);

        $res = array('full_path'=>$this->_path_tmp.$zipPath.'/'.$zipfile, 'file'=>$zipfile, 'error'=>'null', 'err_code'=>0);
        return $res;
  }  
}
